#!/usr/bin/php
<?php
namespace Tug\Controller;

use Plume\Core\Controller;
use Plume\Core\Service;
use Plume\Core\Dao;
use Plume\Application;
require_once __DIR__.'../../../vendor/autoload.php';
class TaskController extends Controller
{
    private $gameSetService;
    private $teamsService;
    private $gameStatusService;
    private $userService;

    public function __construct($app) {
        parent::__construct($app);
        //使用默认Service和默认DAO
        $this->gameSetService = new Service($app, new Dao($app, 'game_set'));
        $this->teamsService = new Service($app, new Dao($app, 'teams'));
        $this->gameStatusService = new Service($app, new Dao($app, 'game_status'));
        $this->userService = new Service($app, new Dao($app, 'user'));
    }
    private function backArgv(&$argv)
    {
        foreach ($argv as $k => $v) {
            if ($k != 0) {
                $argv[$k] = json_decode(base64_decode($v), true);
            }
            continue;
        }
        return $argv;
    }
    public  function updateDetails($argv)
    {
        $this->backArgv($argv);
        $gameInfo = $argv[2];  $redInfo =  $argv[3];
        $blueInfo = $argv[4];  $gameStatusInfo = $argv[5];
        try {
            $sequence = $gameInfo['sequence'];
            $this->gameSetService->beginTransaction();
            $this->teamsService->delete(array('sequence' => $sequence));
            $this->gameSetService->delete(array('sequence' => $sequence));
            $bool = $this->teamsService->insert($redInfo);
            $bool2 = $this->teamsService->insert($blueInfo);
            $bool3 = $this->gameSetService->insert($gameInfo);
            $where = ['sequence' => $sequence];
            $hasOne = $this->gameStatusService->fetch($where);
            $bool4 = true;
            if (empty($hasOne)) {
                $bool4 = $this->gameStatusService->insert($gameStatusInfo);
            }
            if ($bool && $bool2 && $bool3 && $bool4) {
                $this->gameSetService->commitTransaction();
            } else {
                // 重试3次，弱还是失败则记录日志
                $this->gameSetService->rollbackTransaction();
                file_put_contents('task_error.txt',date("Y-m-d H:i:s")."\r\n", 8);
            }
        } catch (\Exception $e) {
            $errData = [$gameInfo, $redInfo, $blueInfo, $gameStatusInfo];
            file_put_contents('task_error.txt',date("Y-m-d H:i:s")."==".json_encode($errData)."\r\n", 8);
        }
    }
    public function gameOver()
    {
        // 游戏结束，将游戏结果，游戏参与用户插入数据库。
    }
}
set_time_limit(0);
ignore_user_abort(true);
file_put_contents('yes.log','通知到了',8);
$app = new Application();
$task = new TaskController($app);
$method = $argv[1];
$task->$method($argv);